<template>
  <div id="chart-card">
    <div class="amount">
      <div style="background-color: rgb(85, 85, 85);">
        <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 6 }" />
        <div v-show="!skeletonIsShow" v-if="$access('ENT_C_MAIN_PAY_DAY_COUNT')" class="amount-top">
          <div class="amount-date">
            <div :class="{'amount-date-active': amountDate === 'today'}" @click="amountDateHandle('today')">今日交易</div>
            <div :class="{'amount-date-active': amountDate === 'yesterday'}" @click="amountDateHandle('yesterday')">昨日交易</div>
          </div>
          <p>成交金额(元)</p>
          <a-tooltip placement="top" color="#fff">
            <template #title>
              <p style="font-size: 20px; margin-bottom: 0;color:#000">{{ payAmountDataAll.payAmount }}</p>
            </template>
            <p style="font-size: 40px;margin-bottom: 35px;color:#fff;width: max-content;">
              {{ amountHandle(payAmountDataAll.payAmount) }}<span v-if="payAmountDataAll.payAmount >=100000000" style="font-size:  20px;font-weight: 600;margin-left: 5px;vertical-align: middle;">亿</span><span v-else-if="payAmountDataAll.payAmount >=10000000" style="font-size:  20px;font-weight: 600;margin-left: 5px;vertical-align: middle;">万</span>
            </p>
          </a-tooltip>
          <div class="amount-list">
            <div><p>成交笔数</p><span>{{ payAmountDataAll.payCount }}</span></div>
            <div><p>退款金额(元)</p><span>{{ payAmountDataAll.refundAmount }}</span></div>
            <div><p>退款笔数</p><span>{{ payAmountDataAll.refundCount }}</span></div>
          </div>
        </div>
        <div class="amount-line" />
        <a-skeleton v-show="skeletonIsShow" active :paragraph="{ rows: 6 }" />
        <div v-show="!skeletonIsShow" v-if="$access('ENT_C_MAIN_PAY_TREND_COUNT')" class="amount-bottom" style="width: 100%">
          <div class="echart-title">
            <div style="display: flex;">
              <b style="color: #fff">趋势</b>
              <a-tooltip class="tooltip">
                <template #title>近期成交金额</template>
                <i class="bi bi-info-circle" style="color:rgba(255, 255, 255, 0.6)" />
              </a-tooltip>
            </div>
            <!--  -->
            <a-select id="selet-date" v-model:value="amountSelectDate" class="date amount-date" placeholder="近30天" @change="amountSelectHandle">
              <a-select-option value="30">近30天</a-select-option>
              <a-select-option value="7">近7天</a-select-option>
            </a-select>
          </div>
          <div v-show="!payAmountEmpty" id="pay-amount" style="width: 100%;" />
          <a-empty v-show="payAmountEmpty" :image="emptyImg" />
        </div>
      </div>
    </div>
    <div class="quantity">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 3 }" />
      <div v-show="!skeletonIsShow" v-if="$access('ENT_C_MAIN_ISV_MCH_COUNT')" class="quantity-top">
        <div class="quantity-title">
          <span> {{ $hasAgentEnt() ? '代理商数量' : '服务商数量' }}</span>
          <a-tooltip class="tooltip">
            <template #title>{{ $hasAgentEnt() ? '代理商数量' : '服务商数量' }}</template>
            <i class="bi bi-info-circle" />
          </a-tooltip>
        </div>
        <div class="quantity-number">
          {{ $hasAgentEnt() ? isvAndMchCount.totalAgent : isvAndMchCount.totalIsv }}
        </div>
      </div>
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 3 }" />
      <div v-show="!skeletonIsShow" class="quantity-bottom">
        <div class="quantity-title">
          <span>商户数量</span>
          <a-tooltip class="tooltip">
            <template #title>商户数量</template>
            <i class="bi bi-info-circle" />
          </a-tooltip>
        </div>
        <div class="quantity-number">
          {{ isvAndMchCount.totalMch }}
        </div>
        <div class="quantity-contrast">
          <div class="contrast-text">
            <span class="especially">
              <span v-show="subMchIsShow" style="margin-right: 5px">特约商户</span>
              <span>{{ isvAndMchCount.isvSubMchCount }}</span>
            </span>
            <span class="ordinary">
              <span v-show="normalMchIsShow" style="margin-right: 5px">普通商户</span>
              <span>{{ isvAndMchCount.normalMchCount }}</span>
            </span>
          </div>
          <!-- 普通商户与特约商户对比图，只有二者数量都不为0时，才显示 -->
          <div v-show="isvAndMchCount.normalMchCount || isvAndMchCount.isvSubMchCount" class="contrast-chart" style="background: #FF8066;">
            <!-- 特约商户色块 -->
            <div
              style="background: #FFD080;cursor: pointer;"
              :style="{width: (isvAndMchCount.isvSubMchCount / isvAndMchCount.totalMch * 100).toFixed(2) + '%'}"
              @mouseover="subMchIsShow = true"
              @mouseleave="subMchIsShow = false"
            />
            <!-- 普通商户色块 -->
            <div
              style="flex-grow: 1;cursor: pointer;"
              @mouseover="normalMchIsShow = true"
              @mouseleave="normalMchIsShow = false"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="personal">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 5 }" />
      <div v-show="!skeletonIsShow">
        <div class="personal-title">
          <img :src="userStore.userInfo.avatarUrl" alt="">
          <div>
            <p>{{ nextAge }}，{{ userStore.userInfo['realname'] }}</p>
            <span>{{ userStore.userInfo['isAdmin'] ? '超级管理员' : '操作员' }}</span>
          </div>
        </div>
        <div class="personal-line" />
        <div class="msg">
          <span>预留信息：<a style="color:#2691FF;margin-right: 5px;" @click="setSafeWord">{{ safeWord?safeWord:'未设置' }}</a>
            <a-tooltip placement="right" title="此信息为你在本站预留的个性信息，用以鉴别假冒、钓鱼网站。如未看到此信息，请立即停止访问并修改密码。如需修改内容请前往个人中心">
              <question-circle-outlined />
            </a-tooltip>
          </span>
        </div>
        <div class="personal-line" />
        <div class="quick-start">
          <p>快速开始</p>
          <ul>
            <li v-for="menu in quickMenuList" :key="menu.entId">
              <router-link :to="menu!.menuUri">{{ menu.entName }}</router-link>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="method">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 6 }" />
      <div v-show="!skeletonIsShow" v-if="$access('ENT_C_MAIN_PAY_TYPE_COUNT')">
        <div class="echart-title">
          <b>支付方式</b>
          <JeepayDateRangePicker v-model:value="payMethodDate" class="date" customDateRangeType="date" :allTimeIsShow="false" @update:value="payMethodDateHandle" />
        </div>
        <div v-show="!payMethodEmpty" id="pay-method" style="width: 100%;height: 100%" />
        <a-empty v-show="payMethodEmpty" :image="emptyImg" />
      </div>
    </div>
    <div class="pay-statistics">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 6 }" />
      <div v-show="!skeletonIsShow" v-if="$access('ENT_C_MAIN_PAY_COUNT')">
        <b>交易统计</b>
        <JeepayDateRangePicker v-model:value="payStatisticsDate" class="date" customDateRangeType="date" :statisticalTimeIsShow="true" @update:value="statisticsHandle" />
        <div v-show="!payStatisticsEmpty" id="pay-statistics" style="width: 100%;height: 100%" />
        <a-empty v-show="payStatisticsEmpty" :image="emptyImg" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { nextTick,  ref, computed, onMounted,getCurrentInstance } from 'vue'
import * as echarts from 'echarts' // 引入图标组件
import { useRouter, useRoute } from 'vue-router'
import { $getPayTrendCount, $getIsvAndMchCount, $getNumCount, $getPayCount, $getPayType,$getUserInfo } from '@/api/manage'
import {pieEcharts, statisticsEcharts, amountEcharts} from './echartsConfig.js' // 图标配置项组件
import { Empty } from 'ant-design-vue' // 缺省图
import { useUserStore } from '@/store/modules/user'
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties
const userStore = useUserStore()
// 获取到路由对象
const router = useRouter() //这是全部路由
// 特约商户 普通商户文字显示与隐藏
let normalMchIsShow = ref(false) // 普通商户
let subMchIsShow = ref(false) // 特约商户
const safeWord = ref('')
onMounted(() =>{
  $getUserInfo().then(res =>{

    safeWord.value = res.safeWord
  })
})
// 切换今日昨日金额数据
let amountDate = ref('today') // 默认为今日
const amountDateHandle = (param) => {
  amountDate.value = param
  numCountHandle() // 切换后调用请求
}

let payAmountDataAll: any = ref({}) // 成交金额总数据（今天和昨天）
const payAmountGetDateData = ( res ) => { //数据赋值
  // 分转元显示
  Object.keys(res.dayCount).forEach(item => {
    if ((item == 'payCount') || (item == 'refundCount')) {
      return
    } else {
      res.dayCount[item] = (res.dayCount[item] / 100).toFixed(2)
    }

  })
  payAmountDataAll.value = res.dayCount
}
// 成交金额请求数据
const numCountHandle = () => {
    $getNumCount({queryDateRange: amountDate.value}).then(res => {
    payAmountGetDateData(res)
  }).catch(err => {
    console.log(err)
  })
}
//设置信息
const setSafeWord = () =>{
  router.push({
    path:'/current/userinfo',
    query:{type:'msg'}
  })
}
// 商户数量
let isvAndMchCount: any = ref({})
const isvAndMchGetData = (res) => {
  isvAndMchCount.value = res
}

let payMethod // 支付方式饼图
let payMethodEmpty = ref(false) // 支付方式饼图缺省图
let payMethodDate = ref('near2now_30') // 饼图日期查询
// 当支付方式自定义日期格式中不包含N ，则代表选择了正确的日期格式
const payMethodDateHandle = () => {
  let flag = payMethodDate.value.indexOf('N') === -1
  if (payMethodDate.value && flag) {
    payMethodHandle(payMethodDate.value)
  }
}
// 饼图数据赋值
const payMethodGetData = (res) => {
  let payTypeData = []
    res[0].length === 0 ? payMethodEmpty.value = true : payMethodEmpty.value = false
    res[0].forEach(item => {
      payTypeData.push({
        value: (item.typeAmount / 100).toFixed(2), // 分转元
        name: item.typeName,
      } as never)
    })

    pieEcharts.series[0].data = payTypeData // 饼图数据赋值
    nextTick(() => {
      payMethod = echarts.init(document.getElementById('pay-method')  as HTMLElement)
      payMethod.setOption(pieEcharts) // 数据填充
    })
}
// 饼图请求数据
const payMethodHandle = (data) => {
  $getPayType(data).then(res => {
    payMethodGetData(res)
  }).catch(err => {
    console.log(err)
  })
}

let payStatistics // 交易统计折线图
let payStatisticsDate = ref('near2now_30') // 交易统计折线图日期查询
let payStatisticsEmpty = ref(false) // 交易统计折线图缺省图
const statisticsHandle = () => {
  let flag = payStatisticsDate.value.indexOf('N') === -1
  if (payStatisticsDate.value && flag) {
    payStatisticsHandle(payStatisticsDate.value)
  }
}
// 交易统计折线图数据赋值
const payStatisticsGetData = (res) => {
  Object.keys(res).length === 0 ? payStatisticsEmpty.value = true : payStatisticsEmpty.value = false
  statisticsEcharts.xAxis.data = res.resDateArr // x轴日期
  let payAmountArr = []
  res.resPayAmountArr.forEach(item => payAmountArr.push((item / 100).toFixed(2) as never)) // 成交金额分转元
  statisticsEcharts.series[0].data = payAmountArr // 成交金额
  statisticsEcharts.series[1].data = res.resPayCountArr // 订单笔数
  let refAmountArr = []
  res.resRefAmountArr.forEach(item => refAmountArr.push((item / 100).toFixed(2) as never)) // 退款金额分转元
  statisticsEcharts.series[2].data = refAmountArr // 退款金额
  nextTick(() => {
    payStatistics = echarts.init(document.getElementById('pay-statistics')  as HTMLElement)
    payStatistics.setOption(statisticsEcharts) //  数据填充
  })
}
// 交易统计折线图请求数据
const payStatisticsHandle = (data) => {
  $getPayCount(data).then(res => {
    payStatisticsGetData(res)
  }).catch(err => {
    console.log(err)
  })
}

// 今日金额折线图日期选择
const amountSelectHandle = (value: string) => {
  payAmountHandle(value)
}
let payAmount // 金额板块折线图
let payAmountEmpty = ref(false) // 金额折线图缺省图是否展示
let amountSelectDate = ref('近30天') // 交易统计折线图日期查询
// 成交金额 数据赋值
const payAmountGetData = (res) => {
  amountEcharts.xAxis.data = res.dateList
  res.dateList.length === 0 ? payAmountEmpty.value = true : payAmountEmpty.value = false
  let payAmountList = []
  res.payAmountList.forEach(item => {payAmountList.push((item / 100).toFixed(2) as never)})
  amountEcharts.series[0].data = payAmountList // 数据赋值
  nextTick(() => {
    payAmount = echarts.init(document.getElementById('pay-amount')  as HTMLElement)
    payAmount.setOption(amountEcharts)
  })
}
// 金额板块折线图请求数据
const payAmountHandle = (date) => {
  $getPayTrendCount(date).then(res => {
    payAmountGetData(res)
  }).catch(err => {
    console.log(err)
  })
}

// 缺省图片的样式
const emptyImg = Empty.PRESENTED_IMAGE_SIMPLE

// 骨架屏是否展示
let skeletonIsShow = ref(true)

// 首页骨架屏隐藏采用 promise all,只有本页面5个请求全部获得数据才会隐藏， 请求顺序依次为：成交金额， 趋势折线图， 商户数量， 支付方式， 交易统计
Promise.all([$getNumCount({queryDateRange: amountDate.value}), $getPayTrendCount(30), $getIsvAndMchCount(), $getPayType(payMethodDate.value), $getPayCount(payStatisticsDate.value)]).then((res) => {
  skeletonIsShow.value = false // 骨架屏取消
  payAmountGetDateData(res[0]) // 成交金额
  payAmountGetData(res[1]) // 趋势折线图
  isvAndMchGetData(res[2]) // 商户数量
  payMethodGetData(res[3]) // 饼图
  payStatisticsGetData(res[4]) // 交易统计
}).catch((error) => {
  skeletonIsShow.value = false // 骨架屏取消
  console.log(error)
})

// 所有图表根据屏幕大小 图表自适应
window.addEventListener('resize', () => {
  payMethod.resize()
  payStatistics.resize()
  payAmount.resize()
})

// 问候语句
const nextAge = computed(() => {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
})
// 快速菜单集合
const quickMenuList: any = computed(() => {
  const result = []

  const putResult = function (item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].menuUri && item[i].quickJump === 1) {
        result.push(item[i] as never)
      }
      if (item[i].children) {
        putResult(item[i].children)
      }
    }
  }

  putResult(userStore.userInfo['allMenuRouteTree'])
  return result
})
// 金额处理 超过1000万时拼接万 超过亿时 拼接亿
const amountHandle = (amount) => {
  if (amount >= 100000000) {
    return parseFloat( (amount / 100000000).toFixed(2) )
  } else if (amount >= 10000000) {
    return parseFloat( (amount / 10000).toFixed(2) )
  } else {
    return amount
  }
}
</script>
<style lang="less" scoped>
  @import './index.less'; // 响应式布局
  // 个人信息页标题
  .personal-title {
    display: flex;
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 15px;
    }
    &>div {
      height: 50px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      p {
        font-size: 15px;
        font-weight: 600;
        margin:0;
      }
    }
  }
  // 个人信息 快速开始
  .quick-start {
    p {
      margin: 0;
      font-weight: bold;
      font-size: 14px;
    }
    ul {
      margin: 0;
      padding: 0;
    }
    li {
      display: inline-block;
      margin-right: 20px;
      margin-top: 20px;
    }
  }

  // 通用图表标题
  .echart-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    b {
      font-size: 14px;
      font-weight: 600;
      margin-right: 10px;
    }
    .date {
      width: 215px
    }
  }

  // 成交金额折线图 日期选择器样式
  // #selet-date .ant-select {
  //   background: rgba(255, 255, 255, 0.05) !important;
  //   color: rgba(255, 255, 255, 0.7) !important;

  // }
  // /deep/ #selet-date .ant-select-arrow {
  //     color: rgba(255, 255, 255, 0.7) !important;
  //   }

  // 交易统计图表标题
  .pay-statistics {
    &>div{
      position: relative;
      &>b, &>.date{
        position: absolute;
        top: 30px;
        z-index: 9
      }
      &>b {
        font-size: 14px;
        font-weight: 600;
        margin-right: 10px;
        top: 36px;
      }
      &>.date {
        width: 215px;
        right: 30px;
      }
    }
  }

  .tooltip {
    &:hover {
      cursor: pointer;
    }
  }

  // 缺省图的样式
  /deep/ .ant-empty-normal {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
  }
</style>
